package kd.bos.kdec.pincar;

import java.math.BigDecimal;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

import kd.bos.bill.MobileBillShowParameter;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.ext.form.control.CustomControl;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import net.sf.json.JSONArray;

/**
 * i拼车行程单
 * 
 * @author zhangyizhe
 *
 */
public class PinCarForMobBill extends AbstractFormPlugin {

	private String[] buttons = new String[] { "startplace", "return", "commit", "deletebill", "incar", "finishtr",
			"linedraw", "generateorder" };

	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		this.addClickListeners(this.buttons);
	}

	@Override
	public void click(EventObject evt) {
		super.click(evt);
		Control control = (Control) evt.getSource();
		String key = control.getKey();
		IFormView view = this.getView();
		IDataModel model = this.getModel();
		long driverId = (long) model.getValue("driverid");
		Map<String, Object> params = new HashMap<>();
		MobileBillShowParameter parameter = (MobileBillShowParameter) this.getView().getFormShowParameter();
		if (StringUtils.equals("deletebill", key)) {// 取消行程单 未被接单才能删除
			Integer orderstatus = Integer.valueOf(model.getValue("orderstatus").toString());
			if (orderstatus != 0 && orderstatus == 1) {
				view.showMessage("本次行程已被接单");
				return;
			} else if (orderstatus != 0 && orderstatus == 2) {
				view.showMessage("本次行程已在路上");
				return;
			} else {// 未接单可以取消
				this.getView().setVisible(false, "deletebill");
				model.setValue("orderstatus", 9);
				Long billPk = (Long) parameter.getPkId();
				DynamicObject obj = BusinessDataServiceHelper.loadSingleFromCache(billPk, "kdec_pincarbill",
						"orderstatus");
				obj.set("orderstatus", 9);// 回写行程单数据状态为取消
				SaveServiceHelper.save(new DynamicObject[] { obj });
			}
		} else if (StringUtils.equals("return", key)) {// 返回 跳父页面
			this.removeDom();// 清空地图dom
			String parentFormId = parameter.getParentFormId().toString();
			params.put("formId", parentFormId);
			this.showForm(params, null);
		} else if (StringUtils.equals("commit", key)) {// 提交跳行程单列表 发布行程
			this.removeDom();// 清空地图dom
			params.put("formId", "kdec_pincarbilllist");
			this.showForm(params, null);
		} else if (StringUtils.equals("incar", key)) {// 我已上车
			view.setVisible(false, "deletebill");
			view.setVisible(false, "incar");
			view.setVisible(true, "finishtr");
			model.setValue("orderstatus", 2);
			// 更新行程单状态
			Object billPk =  parameter.getPkId();
			DynamicObject obj = BusinessDataServiceHelper.loadSingleFromCache(billPk, "kdec_pincarbill", "orderstatus");
			obj.set("orderstatus", 2);// 回写行程单数据状态为在路上
			SaveServiceHelper.save(new DynamicObject[] { obj });
			// 回写订单状态
			QFilter filter = new QFilter("billpkid", QCP.equals, String.valueOf(billPk));// 利用关联主键订单中的billpkid(行程单id)
			DynamicObject objOrder = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincarorder", "orderstatus",
					filter.toArray());
			objOrder.set("orderstatus", 1);// 回写订单单数据状态为在路上
			SaveServiceHelper.save(new DynamicObject[] { objOrder });
		} else if (StringUtils.equals("finishtr", key)) {// 行程结束
			view.setVisible(false, "finishtr");
			model.setValue("orderstatus", 3);
			this.removeDom();// 清空地图dom
			// 更新行程单状态
			Long billPk = (Long) parameter.getPkId();
			DynamicObject obj = BusinessDataServiceHelper.loadSingleFromCache(billPk, "kdec_pincarbill", "orderstatus");
			obj.set("orderstatus", 3);
			SaveServiceHelper.save(new DynamicObject[] { obj });
			// 回写订单状态
			QFilter filter = new QFilter("billpkid", QCP.equals, String.valueOf(billPk));
			DynamicObject objOrder = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincarorder",
					"orderstatus,id,creator", filter.toArray());
			objOrder.set("orderstatus", 2);
			SaveServiceHelper.save(new DynamicObject[] { objOrder });
			// 更新乘客积分
			long userId = Long.parseLong(RequestContext.get().getUserId());
			long orgId = RequestContext.get().getOrgId();
			QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
			reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
			DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
					reportfilter.toArray());// 查乘客信息统计表
			if (null == report) {// 无数据，新增
				report = BusinessDataServiceHelper.newDynamicObject("kdec_pincar_reportbill");// 表单标识
				// 设置单据属性
				report.set("billno", System.currentTimeMillis());
				report.set("billstatus", "B");
				report.set("creator", userId);
				report.set("orgfield", RequestContext.get().getOrgId());
				report.set("kmsnum", Double.valueOf(model.getValue("distsance").toString()));
			} else if (report != null) {// 有数据更新
				// 累加计算乘客积分
				BigDecimal kmsnum = new BigDecimal(report.getString("kmsnum"));
				BigDecimal kmsnumNew = kmsnum.add(new BigDecimal(model.getValue("distsance").toString()));
				report.set("kmsnum", kmsnumNew);
			}
			SaveServiceHelper.save(new DynamicObject[] { report });
			// 查订单人数
			QFilter memfilter = new QFilter("creator", QCP.equals, driverId);
			memfilter.and(new QFilter("orderstatus", QCP.equals, "1"));// 统计在路上的数量
			DynamicObject[] memObjs = BusinessDataServiceHelper.load("kdec_pincarorder", "memnum", memfilter.toArray());
			int allmemnum = 0;
			int memnum = Integer.valueOf(model.getValue("memnum").toString());// 我的人数
			allmemnum += memnum;
			for (DynamicObject dynamicObject : memObjs) {
				allmemnum += dynamicObject.getInt("memnum");// 加拼车人数
			}
			int cost = Integer.valueOf(model.getValue("taxicostf").toString());
			int costpin = cost / (allmemnum + 1);// 计算价钱
			String ordercost = (costpin * memnum) + "";

			Map<String, Object> custs = new HashMap<>();
			custs.put("ordercost", ordercost);
			custs.put("driverid", driverId);
			custs.put("pk", billPk);
			params.put("formId", "kdec_pincar_payforbill");// 跳转支付
			this.showForm(params, custs);
		} else if (StringUtils.equals("linedraw", key)) {// 查看路线
			this.getView().setVisible(true, "map");//展示地图
		} else if (StringUtils.equals("generateorder", key)) {// 接单
			long userId = Long.parseLong(RequestContext.get().getUserId());
			FormShowParameter parameterv = this.getView().getFormShowParameter();
			long pk = (long) parameterv.getCustomParam("pk");
			DynamicObject obj = BusinessDataServiceHelper.loadSingleFromCache(pk, "kdec_pincarbill");
			QFilter detailFilter = new QFilter("creator", QCP.equals, userId);
			DynamicObject detail = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincardetailbill", "seatnum",
					detailFilter.toArray());
			int seatnum = detail.getInt("seatnum");
			QFilter filter = new QFilter("creator", QCP.equals, userId);
			filter.and(new QFilter("orderstatus", QCP.equals, 0));
			filter.and(new QFilter("traveldate", QCP.equals, obj.get("traveldate")));//按日期隔离
			//计算车能接的人
			DynamicObject[] orderObjs = BusinessDataServiceHelper.load("kdec_pincarorder", "memnum", filter.toArray());
			if (obj.getInt("memnum") > seatnum) {
				view.showMessage("接单人数大于座位数");
				return;
			} else if (obj.getInt("memnum") <= seatnum) {
				// 计算座位数
				if (null != orderObjs && orderObjs.length > 0) {
					int memnum = 0;
					for (DynamicObject dynamicObject : orderObjs) {
						memnum += dynamicObject.getInt("memnum");
					}
					if (memnum != 0) {
						if (memnum >= seatnum || (memnum + obj.getInt("memnum")) > seatnum) {
							Map<String, Object> formId = new HashMap<>();
							formId.put("formId", "kdec_pincartan");
							FormShowParameter showParameter = FormShowParameter.createFormShowParameter(formId);
							showParameter.getOpenStyle().setShowType(ShowType.Modal);
							view.showForm(showParameter);
							return;
						}
					}
				}
			}
			//向下传递乘客信息到订单
			Map<String, Object> data = new HashMap<>();
			data.put("startplace", model.getValue("startplace").toString());// 出发地
			data.put("endplace", model.getValue("endplace"));// 目的地
			data.put("traveldate", model.getValue("traveldate"));// 出发日期
			data.put("timefield", model.getValue("timefield"));// 时间
			data.put("memnum", model.getValue("memnum").toString());// 人数
			data.put("distsance", model.getValue("distsance") + "km");// 距离
			data.put("taxicost", model.getValue("taxicost"));// 推荐车费
			DynamicObject creator = (DynamicObject) model.getValue("creator");
			data.put("phone", creator.get("phone"));// 乘客手机号
			data.put("pk", pk);// 行程单主键ID
			params.put("formId", "kdec_pincarordermob");
			this.showForm(params, data);
		}
	}

	@Override
	public void afterBindData(EventObject e) {
		super.afterBindData(e);
		IDataModel model = this.getModel();
		IFormView view = this.getView();
		FormShowParameter parameter = this.getView().getFormShowParameter();
		Map<String, Object> custParam = parameter.getCustomParams();
		if ((custParam.size() != 0 && null != custParam.get("startplacetext"))) {// 判断是否有地点坐标
			Map<String, Object> params = parameter.getCustomParams();
//			if (!params.containsKey("distance")||!params.containsKey("traveltime")){
//				this.getView().showTipNotification("无适配路线！");
//
//			}
			String dist = this.distMath(params);
			model.setValue("startplace", params.get("startplacetext").toString());
			model.setValue("endplace", params.get("endplacetext").toString());
			model.setValue("taxicost", params.get("taxicost").toString());
			model.setValue("taxicostf", params.get("taxicostf"));
			model.setValue("orderstatus", 0);
			model.setValue("dist", dist);
			String startpos = params.get("startpos").toString();
			String endpos = params.get("endpos").toString();
			model.setValue("startpos", startpos);// 坐标预存
			model.setValue("endpos", endpos);
			if (!StringUtils.equals("", model.getValue("endpos").toString())
					&& !StringUtils.equals("", model.getValue("startpos").toString())) {
				// 绘制地图
				CustomControl mapcon = (CustomControl) this.getControl("customcontrolap");
				Map<String, Object> map = new HashMap<>();
				JSONArray startposArr = JSONArray.fromObject(startpos);
				JSONArray endposArr = JSONArray.fromObject(endpos);
				map.put("action", "billdraw");
				map.put("startpos", startposArr);
				map.put("endpos", endposArr);
				mapcon.setData(map);
			}
		}
		if (parameter.getParentFormId().equals("kdec_pincar_driver")) {// 判断父单据体是否是司机端
			view.setVisible(false, "deletebill");// 只有乘客能取消行程
			view.setVisible(true, "generateorder");// 司机才能接单
		}
		if (Integer.valueOf(model.getValue("orderstatus").toString()) > 0) {// 接单状态0:待接单1:已接单2:在路上3:已完成9:已取消
			if (Integer.valueOf(model.getValue("orderstatus").toString()) == 1) {// 1:已接单
				view.setVisible(true, "incar");// 展示上车
			} else if (Integer.valueOf(model.getValue("orderstatus").toString()) == 2) {// 2:在路上
				view.setVisible(false, "incar");
				view.setVisible(true, "finishtr");// 行程结束
			}
			view.setVisible(false, "deletebill");
			long driverid = (long) model.getValue("driverid");// 有司机接单才有这个id
			if (0 != driverid) {
				view.setVisible(true, "flexpanelap");// 展示司机信息
				model.setValue("driverfield", driverid);
				QFilter filter = new QFilter("creator", QCP.equals, driverid);
				DynamicObject obj = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincardetailbill",
						"telephone,carbrand,cartype,carcolor,carnum,name", filter.toArray());
				Label name = this.getControl("name");
				name.setText(obj.getString("name"));
				Label tel = this.getControl("telephone1");
				tel.setText("手机号：" + obj.getString("telephone"));
				Label carnum = this.getControl("carnum");
				carnum.setText(obj.getString("carnum"));
				Label cardata = this.getControl("cardata");
				cardata.setText(obj.getString("carcolor") + "·" + obj.getString("carbrand") + " "
						+ obj.getString("cartype") + " ");
			}

		}

	}

	/**
	 * 页面跳转通用方法
	 * 
	 * @param formid
	 *            页面标识
	 * @param closeActionId
	 *            close回写标识
	 * @param customParams
	 *            传入下个页面参数
	 */
	private void showForm(Map<String, Object> params, Map<String, Object> customParams) {
		Map<String, Object> formId = new HashMap<>();
		formId.put("formId", params.get("formId"));
		FormShowParameter showParameter = FormShowParameter.createFormShowParameter(formId);
		showParameter.getOpenStyle().setShowType(ShowType.Floating);
		if (null != params.get("closeActionId")) {
			CloseCallBack closeCallBack = new CloseCallBack(this, params.get("closeActionId").toString());
			showParameter.setCloseCallBack(closeCallBack);
		}
		if (null != customParams) {
			showParameter.setCustomParams(customParams);
		}
		this.getView().showForm(showParameter);
	}

	/**
	 * 清除地图dom元素 ps:离开页面清除dom防止不清空页面，下次进入不加载自定义控件
	 */
	private void removeDom() {
		CustomControl mapCon = (CustomControl) this.getControl("customcontrolap");
		Map<String, Object> map = new HashMap<>();
		map.put("listReturn", 1);
		mapCon.setData(map);// 清空地图dom
	}

	/**
	 * 計算時間以及距離返回
	 * 
	 * @param params
	 * @return
	 */
	private String distMath(Map<String, Object> params) {

		double m = Double.valueOf(params.get("distance").toString());
		double km = Math.rint(m / 100) / 10;// 这个结果是你要的千米
		String str = params.get("traveltime").toString();
		int seconds = Integer.parseInt(str);
		int temp = 0;
		StringBuffer sb = new StringBuffer();
		temp = seconds / 3600;
		sb.append((temp < 1) ? "" : temp + "小时");
		temp = seconds % 3600 / 60;
		sb.append((temp < 1) ? "" : temp + "分钟");
		String dist = "全程约" + String.valueOf(km) + "公里，预计时间" + sb.toString();
		this.getModel().setValue("distsance", String.valueOf(km));
		return dist;
	}
}
